<template>
    <div class="global-box table-card">
        <div v-loading="loading" class="global-box-table" pr-5px>
            <div ref="box" class="box text-align-left h-full" flex flex-col>
                <div class="search-box">
                    <el-form :model="searchForm" inline size="small">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="searchForm.name" placeholder="请输入姓名" />
                        </el-form-item>
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="searchForm.phone" placeholder="请输入手机号" />
                        </el-form-item>
                        <el-form-item label="区域" prop="province">
                            <el-select
                                style="width: 190px"
                                v-model="searchForm.province"
                                filterable
                                placeholder="请选择区域"
                            >
                                <el-option label="全部" value="all" />
                                <el-option
                                    v-for="item in area_list"
                                    :key="item.adcode"
                                    :label="item.name"
                                    :value="item.name"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="状态" prop="status">
                            <el-select
                                style="width: 190px"
                                v-model="searchForm.status"
                                placeholder="请选择状态"
                            >
                                <el-option label="全部" value="all" />
                                <el-option label="正常" value="1" />
                                <el-option label="禁用" value="0" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="getListData">查询</el-button>
                            <el-button type="success" @click="showDialog('add')">新增</el-button>
                        </el-form-item>
                        <el-form-item> </el-form-item>
                    </el-form>
                </div>
                <div class="table-box flex-1 overflow-hidden">
                    <el-table :data="list" border stripe height="100%" size="small">
                        <el-table-column type="index" width="80" label="序号" align="center" />
                        <el-table-column prop="name" label="姓名" />
                        <el-table-column prop="phone" label="手机号" />
                        <el-table-column prop="province" label="区域" />
                        <el-table-column prop="status" label="状态" align="center">
                            <template #default="scope">
                                <el-text
                                    :type="scope.row.status === 1 ? 'primary' : 'danger'"
                                    p-0
                                    >{{ scope.row.status === 1 ? "正常" : "禁用" }}</el-text
                                >
                            </template>
                        </el-table-column>
                        <el-table-column prop="create_at" label="创建时间" align="center">
                            <template #default="scope">
                                {{ stickUtils.dateFormat(scope.row.create_at - 0) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="240">
                            <template #default="{ row }">
                                <el-link
                                    :disabled="row.status === 1"
                                    type="primary"
                                    @click="handleEnable(row)"
                                    underline="never"
                                    >启用</el-link
                                >
                                <el-link
                                    :disabled="row.status === 0"
                                    type="primary"
                                    @click="handleDisable(row)"
                                    underline="never"
                                    >禁用</el-link
                                >
                                <el-link
                                    :disabled="row.status !== 1"
                                    type="success"
                                    underline="never"
                                    @click="handleAssign(row)"
                                    >分配杆号</el-link
                                >
                                <el-link type="danger" @click="handleDelete(row)" underline="never"
                                    >删除</el-link
                                >
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="pt-[15px]">
                    <el-pagination
                        v-model:current-page="page.index"
                        class="system-page"
                        background
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="page.total"
                        :page-size="page.size"
                        :page-sizes="[10, 20, 50, 100]"
                        @current-change="onCurrentChange"
                        @size-change="onSizeChange"
                    />
                </div>
            </div>
        </div>
        <DataForm
            @submitSuccess="getListData"
            v-model:visible="dialogVisible"
            :model="dialogModel"
            :value="dialogValue"
        />

        <DataNumber
            v-model:visible="assignVisible"
            :seller-id="assignSellerId"
            :seller-name="assignSellerName"
            :province="assignProvince"
        />
    </div>
</template>

<script lang="ts" setup>
import type { GlobalTablePage } from "~/types/components.types";
import { area_list } from "./province";
import DataForm from "./DataForm.vue";
import DataNumber from "./DataNumber.vue";

const [loading, toggleLoading] = useToggle(false);

const list = ref<Stick.ISeller[]>([]);
const box = useTemplateRef<HTMLDivElement>("box");
const page: GlobalTablePage = reactive({
    index: 1,
    size: 20,
    total: 0
});
const searchForm = ref({
    name: "",
    phone: "",
    province: "all",
    status: "all"
});

const dialogVisible = ref(false);
const dialogModel = ref<"add" | "edit" | "view">("add");
const dialogValue = ref<any>({});

const assignVisible = ref(false);
const assignSellerId = ref<string | number>("");
const assignSellerName = ref<string>("");
const assignProvince = ref<string>("");

const showDialog = (model: "add" | "edit" | "view") => {
    dialogModel.value = model;
    dialogValue.value = {
        name: "",
        phone: "",
        province: ""
    };
    dialogVisible.value = true;
};

async function getListData() {
    const { stop } = useTimeoutFn(() => toggleLoading(true), 200);
    const { success, data } = await sellClient.sellerPageList({
        current: page.index,
        pageSize: page.size,
        ...searchForm.value,
        province: searchForm.value.province === "all" ? "" : searchForm.value.province,
        status: searchForm.value.status === "all" ? "" : searchForm.value.status
    });
    stop();
    toggleLoading(false);
    if (success) {
        page.total = data.total;
        list.value = data.list || [];
    }
}

// 分页相关：监听页码切换事件
function onCurrentChange(val: number) {
    page.index = val;
    getListData();
}
// 分页相关：监听单页显示数量切换事件
function onSizeChange(val: number) {
    page.size = val;
    page.index = 1;
    getListData();
}

const handleEnable = async (row: any) => {
    let confirm;
    try {
        confirm = await ElMessageBox.confirm("确认启用吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        });
    } catch (_error) {
        confirm = false;
    }

    if (!confirm) return;

    try {
        const res = await sellClient.enableApi(row.id);
        if (res.success) {
            ElMessage.success("启用成功");
            getListData();
        } else {
            ElMessage.error(res.message || "启用失败");
        }
    } catch (error) {
        console.log(error);
        ElMessage.error("启用失败");
    }
};

const handleDisable = async (row: any) => {
    let confirm;
    try {
        confirm = await ElMessageBox.confirm("确认禁用吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        });
    } catch (_error) {
        confirm = false;
    }

    if (!confirm) return;

    try {
        const res = await sellClient.disableApi(row.id);
        if (res.success) {
            ElMessage.success("禁用成功");
            getListData();
        } else {
            ElMessage.error(res.message || "禁用失败");
        }
    } catch (error) {
        console.log(error);
        ElMessage.error("禁用失败");
    }
};

const handleDelete = async (row: any) => {
    let confirm;
    try {
        confirm = await ElMessageBox.confirm("确认删除吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        });
    } catch (_error) {
        confirm = false;
    }

    if (!confirm) return;

    try {
        const res = await sellClient.deleteApi(row.id);
        if (res.success) {
            ElMessage.success("删除成功");
            getListData();
        } else {
            ElMessage.error(res.message || "删除失败");
        }
    } catch (error) {
        console.log(error);
        ElMessage.error("删除失败");
    }
};

const handleAssign = (row: any) => {
    assignSellerId.value = row.id;
    assignSellerName.value = row.name;
    assignProvince.value = row.province;
    assignVisible.value = true;
};

getListData();
</script>

<style lang="scss" scoped>
.el-link {
    + .el-link {
        margin-left: 10px;
    }
}
</style>
